package android.slc.appbase.ui

import android.slc.box.core.property.WrapDataChangeListener
import android.slc.box.core.virtual_android.Bundle
import android.slc.box.core.ui.BaseStageView
import android.slc.module.component.mock.MockManager
import cn.hutool.core.collection.CollectionUtil
import de.saxsys.mvvmfx.FxmlView
import de.saxsys.mvvmfx.Scope
import de.saxsys.mvvmfx.ViewModel
import javafx.scene.layout.Pane

/**
 * @author slc
 * @date 2022/03/21 下午 3:34
 */
abstract class AppView<VM : AppViewModel> : BaseStageView<VM>() {

    override fun finishView() {
        if (boxContentPane == screenRootPane || boxContentPane.parent == null) {
            finish()
            return
        }
        if (boxContentPane.parent == screenRootPane && CollectionUtil.size(screenRootPane.children) == 1) {
            finish()
            return
        }
        (boxContentPane.parent as Pane).children.remove(boxContentPane)
    }

    fun <ViewType : FxmlView<out ViewModelType>?, ViewModelType : ViewModel?> addView2CurrentPane(
        viewClass: Class<ViewType>?,
        vararg scopes: Scope?
    ) {
        this.addView(
            boxContentPane,
            viewClass,
            *scopes
        )
    }

    fun <ViewType : FxmlView<out ViewModelType>?, ViewModelType : ViewModel?> launcherWindow(
        viewClass: Class<ViewType>?,
        appStageLauncherConfig: AppStageLauncherConfig,
        vararg scopes: Scope?
    ) {
        this.launcherWindow(
            viewClass,
            appStageLauncherConfig,
            bundle = null,
            *scopes
        )
    }

    fun <ViewType : FxmlView<out ViewModelType>?, ViewModelType : ViewModel?> launcherWindow(
        viewClass: Class<ViewType>?,
        appStageLauncherConfig: AppStageLauncherConfig,
        bundle: Bundle?,
        vararg scopes: Scope?
    ) {
        this.launcherWindow(
            appStageLauncherConfig.createCurrentStage(),
            viewClass,
            appStageLauncherConfig,
            bundle,
            *scopes
        )
    }

    override fun onBindViewLater() {
        super.onBindViewLater()
        registerMockHeartbeatListener()
    }

    override fun onDestroy() {
        super.onDestroy()
        MockManager.getInstance().unRegisterMockHeartbeatListener(mockHeartbeatListener)
    }

    /**模拟数据心跳**/
    private val mockHeartbeatListener = WrapDataChangeListener<Void> {
        onMockHeartbeat()
    }

    private fun registerMockHeartbeatListener() {
        if (MockManager.getInstance().isUseMock) {
            MockManager.getInstance().registerMockHeartbeatListener(mockHeartbeatListener)
        }
    }

    protected open fun onMockHeartbeat() {

    }

}
